<template>
  <div>
    <div>
      <div
        class="crud-group"
      >
        <!-- 搜索 -->
        <el-input
          v-model="query.cmName"
          clearable
          size="small"
          placeholder="集群名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
        <!-- <rrOperation :crud="crud" /> -->
        <el-button
          icon="el-icon-search"
          type="success"
          @click="crud.toQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="crud.toAdd"
        >新增</el-button>
        <el-button
          icon="el-icon-refresh-left"
          type="warning"
          @click="crud.resetQuery"
        >重置</el-button>
        <el-button
          style="margin-left: auto;"
          type="primary"
          icon="el-icon-refresh"
          @click="refreshCluster"
        >集群配置刷新</el-button>
      </div>
      <!-- <crudOperation :permission="permission">
        <template v-slot:more>
          <Operation :permission="permission" />
        </template>
      </crudOperation> -->
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        style="width: 100%"
        @select="selectChange"
        @selection-change="crud.selectionChangeHandler"
        @current-change="handleCurrentChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          v-if="columns.visible('centerName')"
          prop="centerName"
          label="中心名称"
          show-overflow-tooltip
        />
        <el-table-column
          prop="areaId"
          label="分组"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ getAreaName(scope.row.areaId) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('cmFlag')"
          prop="cmFlag"
          label="集群标识"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="columns.visible('cmName')"
          prop="cmName"
          label="集群名称"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="columns.visible('component')"
          prop="component"
          label="组件"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="getTarget(scope.row)"
            >组件配置</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="columns.visible('clusterName')" prop="clusterName" label="集群信息" show-overflow-tooltip />
        <el-table-column
          v-if="columns.visible('clusterHostInfo')"
          prop="clusterHostInfo"
          label="元数据库信息维护"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag @click="showMetaDbInfo(scope.row.cmFlag, scope.row.clusterFlag)">
              {{ '元数据库信息维护' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('clusterHostInfo')"
          prop="clusterHostInfo"
          label="集群主机信息维护"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag @click="showHostInfo(scope.row.cmFlag,scope.row.centerId)">
              {{ '集群主机信息维护' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <!-- <el-table-column
          v-if="columns.visible('clusterQueueInfo')"
          prop="clusterQueueInfo"
          label="队列用户机构维护"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag @click="showUserUnitInfo(scope.row.cmFlag,scope.row.centerId)">
              {{ '队列用户机构维护' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <!-- <el-table-column
          v-if="columns.visible('clusterAdInfo')"
          prop="clusterAdInfo"
          label="AD配置信息维护"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag @click="showAdInfo(scope.row.cmFlag,scope.row.centerId)">
              {{ 'AD配置信息维护' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column
          v-if="columns.visible('monitorFlag')"
          label="监控状态"
          align="center"
          prop="monitorFlag"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.monitorFlag"
              active-value="1"
              inactive-value="0"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeMonitorFlag(scope.row.cmFlag, scope.row.centerId, scope.row.monitorFlag)"
            /></template>
        </el-table-column>
        <!-- <el-table-column  label="集群认证配置维护" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="upload(scope.row)">上传文件</el-button>
          </template>
        </el-table-column> -->

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="editRow(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              style="color:red"
              @click="deleteRow(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <pagination />
      </div>

      <el-dialog
        :close-on-click-modal="false"
        :before-close="closeApplyInfoDialog"
        :visible.sync="open"
        title="上传文件"
        width="800px"
      >
        <el-form
          ref="form"
          label-width="120px"
          :model="tableData"
          :rules="rules"
        >
          <el-form-item label="集群名称">
            <el-input
              v-model="tableData.cmName"
              style="width:560px"
              disabled
            />
          </el-form-item>
          <el-form-item
            label="集群信息"
            prop="clusterName"
          >
            <el-select
              v-model="tableData.clusterName"
              placeholder="请选择集群"
              style="width:560px"
            >
              <el-option
                v-for="item in tableList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文件上传">
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="checkType"
              :on-change="getList"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">只能上传 conf 文件，且不超过 1M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeApplyInfoDialog">取 消</el-button>
            <el-button
              type="primary"
              @click="uploadData"
            >确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        :close-on-click-modal="false"
        :before-close="libraryClose"
        :visible.sync="libraryFlag"
        title="元数据库信息维护"
        width="800px"
      >
        <el-form label-width="120px">
          <el-form-item label="服务器地址">
            <el-select
              v-model="libraryForm.clusterFlag"
              placeholder="请选择"
              style="width:560px"
              @change="clusterFlagChange"
            >
              <el-option
                v-for="item in clusterFlagList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="服务器地址">
            <el-input
              v-model="libraryForm.address"
              style="width:560px"
            />
          </el-form-item>
          <el-form-item label="用户名">
            <el-input
              v-model="libraryForm.user"
              style="width:560px"
            />
          </el-form-item>
          <el-form-item label="密码">
            <el-input
              v-model="libraryForm.password"
              type="password"
              style="width:560px"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="libraryClose">取 消</el-button>
            <el-button
              type="primary"
              @click="submitMetaDbInfo"
            >确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <addForm ref="addForm" />
    <hostInfoForm ref="hostInfoForm" />
    <userUnitForm ref="userUnitForm" />
    <adInfoForm ref="adInfoForm" />
    <el-dialog
      :close-on-click-modal="false"
      :before-close="moduleClose"
      :visible.sync="moduleFlag"
      title="组件范围"
      width="1000px"
    >
      <el-tabs
        v-model="activeName"
        style="width:80%"
        @tab-click="handleClick"
      >
        <el-tab-pane
          v-for="item in activeList"
          :key="item"
          :label="item"
          :name="item"
        >
          <el-row>
            <el-col
              :span="10"
              style="border-right:2px solid #e4e7ed"
            >
              <el-tree
                :data="treeData"
                :props="defaultProps"
                show-checkbox
                :default-checked-keys="checkedList"
                node-key="id"
                highlight-current
                @check-change="solrChange"
                @node-click="solrClick"
              />
            </el-col>
            <el-col :span="14">
              <el-form
                :inline="true"
                label-width="220px"
              >
                <el-form-item label="预警值">
                  <el-input
                    :value="editData.alarmValue"
                    placeholder="请输入"
                    style="width:200px"
                    @input="handleAlarmChange"
                  />%
                </el-form-item>
                <el-form-item
                  label="总数"
                >
                  <el-input
                    :value="editData.defaultValue"
                    placeholder="请输入"
                    style="width:200px"
                    @input="handleDefaultChange"
                  />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="moduleClose"
        >取 消</el-button>
        <el-button
          type="primary"
          @click="saveEdit"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import clusterWh from '@/api/monitor/clusterWh'
import addForm from './addForm.vue'
import hostInfoForm from './hostInfoForm.vue'
import userUnitForm from './userUnitForm.vue'
import adInfoForm from './adInfoForm.vue'
import CRUD, { presenter, header, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import parameter from '@/api/phaseTwo/parameter.js'

// crud交由presenter持有
const clusterwhCrud = CRUD({
  title: '监控主机信息维护',
  url: 'monitor_api/clusterwh/selCmInfo',
  crudMethod: { ...clusterWh }
})
export default {
  name: 'Index',
  components: { addForm, hostInfoForm, pagination, userUnitForm, adInfoForm },
  mixins: [presenter(clusterwhCrud), crud(), header()],
  data() {
    return {
      monitorFlag: '',
      permission: {
        add: ['admin', 'clusterWh:add'],
        edit: ['admin', 'clusterWh:edit'],
        del: ['admin', 'clusterWh:del'],
        enable: ['admin', 'clusterWh:enable'],
        disable: ['admin', 'clusterWh:disable'],
        moreOpe: ['clusterWh:edit', 'clusterWh:del', 'roles:enable']
      },
      queryOptions: [
        {
          columnName: 'cmName',
          columnValue: 'cm集群名称',
          inputType: 1
        }
      ],
      open: false,
      tableData: {
        cmName: '',
        clusterName: ''
      },
      rules: {
        clusterName: [{ required: true, message: '请选择集群信息', trigger: 'change' }]
      },
      tableList: [],
      fileList: [],
      files: null,
      libraryFlag: false,
      clusterFlagList: [],
      libraryForm: {
        cmFlag: '',
        clusterFlag: '',
        address: '',
        user: '',
        password: ''
      },
      lineData: {},
      activeList: [],
      allData: [],
      activeName: '',
      activeDataId: '',
      moduleFlag: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      componentsToChange: {
        hbase: [],
        hdfs: [],
        hive: [],
        impala: [],
        yarn: [],
        zooKeeper: [],
        other: []
      }
    }
  },
  computed: {
    checkedList() {
      const arr = []
      this.componentsToChange[this.activeName].forEach((item) => {
        if (item.sign === '1') {
          arr.push(item.id)
        }
      })
      return arr
    },
    treeData() {
      const data = []
      this.componentsToChange[this.activeName].forEach((val, index) => {
        data.push({id: val.id, label: val.targetName, data: val})
      })
      return data
    },
    editData() {
      const data = {
        alarmValue: '',
        defaultValue: ''
      }
      this.componentsToChange[this.activeName].forEach((val) => {
        if (val.targetCode === this.activeDataId) {
          data.alarmValue = val.alarmValue
          data.defaultValue = val.defaultValue
        }
      })
      return data
    }
  },
  // 数据字典
  created() {
    // this.crud.queryList = this.queryOptions
    // parameter.getClusterService({current: 1, size: 10}).then(res => { console.log(res) })
  },
  methods: {
    handleAlarmChange(val) {
      this.componentsToChange[this.activeName].forEach((item) => {
        if (item.targetCode === this.activeDataId) {
          item.alarmValue = val
        }
      })
    },
    handleDefaultChange(val) {
      this.componentsToChange[this.activeName].forEach((item) => {
        if (item.targetCode === this.activeDataId) {
          item.defaultValue = val
        }
      })
    },
    editRow(data) {
      this.crud.toEdit(data)
    },
    deleteRow(data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.doDelete([data])
      }).catch(() => {
      })
    },
    handleClick(data) {
      this.activeName = data.name
      this.activeDataId = this.componentsToChange[data.name][0].targetCode
    },
    saveEdit() {
      const cmTargetList = []
      for (const item in this.componentsToChange) {
        this.componentsToChange[item].forEach((val) => {
          if (val.sign === '1') {
            const value = {
              ...val,
              alarmValue: val.alarmValue / 100
            }
            cmTargetList.push(value)
          }
        })
      }
      const obj = {centerId: this.lineData.centerId, clusterFlag: this.lineData.clusterFlag, cmFlag: this.lineData.cmFlag, cmTargetList}
      parameter.saveTarget(obj).then((res) => {
        if (res) {
          this.$notify({
            title: '成功',
            message: '修改' + res + '条成功',
            type: 'success'
          })
        }
        this.moduleFlag = false
        this.checkList = []
      })
    },
    solrChange(data, checked) {
      this.componentsToChange[this.activeName].forEach((item) => {
        if (item.id === data.id) {
          item.sign = checked ? '1' : '0'
        }
      })
    },
    solrClick(node) {
      this.activeDataId = node.data.targetCode
    },
    moduleClose() {
      this.checkList = []
      this.moduleFlag = false
    },
    getTarget(row) {
      this.lineData = row
      this.activeList = []
      this.componentsToChange = []
      parameter.getTarget(row.cmFlag, row.clusterFlag).then((res) => {
        this.allData = res
        res.forEach((item) => {
          this.activeList.push(item.serviceType)
          item.cmTargetList.forEach((val) => {
            val.alarmValue = val.alarmValue * 100
          })
          this.componentsToChange[item.serviceType] = item.cmTargetList
        })
        
        this.activeName = this.activeList[0]
        this.activeDataId = this.componentsToChange[this.activeName][0].targetCode
        this.moduleFlag = true
      })
    },
    showMetaDbInfo(cmFlag, clusterFlag) {
      this.libraryFlag = true
      this.libraryForm.cmFlag = cmFlag
      this.clusterFlagList = clusterFlag.split(',')
    },
    clusterFlagChange() {
      var params = {
        cmFlag: this.libraryForm.cmFlag,
        clusterFlag: this.libraryForm.clusterFlag
      }
      clusterWh.queryHiveMetastore(params).then(rsp => {
        if (rsp !== undefined) {
          this.libraryForm.address = rsp.address
          this.libraryForm.user = rsp.user
          this.libraryForm.password = rsp.password
        }
      }).catch(_ => {
        this.$notify.$message.error({
          message: '获取元数据库信息失败'
        })
      })
    },
    submitMetaDbInfo() {
      clusterWh.saveHiveMetastore(this.libraryForm)
      this.libraryForm = {
        cmFlag: '',
        clusterFlag: '',
        address: '',
        user: '',
        password: ''
      }
      this.libraryFlag = false
    },
    showHostInfo(cmFlag, centerId) {
      this.$refs.hostInfoForm.cmFlag = cmFlag
      this.$refs.hostInfoForm.centerId = centerId
      this.$refs.hostInfoForm.hostInfoFlag = true
    }, showUserUnitInfo(cmFlag, centerId) {
      this.$refs.userUnitForm.cmFlag = cmFlag
      this.$refs.userUnitForm.centerId = centerId
      this.$refs.userUnitForm.flag = true
    }, showAdInfo(cmFlag, centerId) {
      this.$refs.adInfoForm.cmFlag = cmFlag
      this.$refs.adInfoForm.centerId = centerId
      this.$refs.adInfoForm.flag = true
    }, handleCurrentChange(val) {
      const tClusterFlags = val.clusterFlag.split(',')
      const tClusterNames = val.clusterName.split(',')
      const tImpalaTotalGB = val.impalaTotalGB.split(',')
      const clusterList = []
      for (let i = 0; i < tClusterFlags.length; i++) {
        const clusterInfo = { 'clusterFlag': tClusterFlags[i], 'clusterName': tClusterNames[i], 'id': i, 'impalaTotalGB': tImpalaTotalGB[i] }
        clusterList.push(clusterInfo)
      }
      this.$refs.addForm.addForm = val
      this.$refs.addForm.clusterList = clusterList
    }, [CRUD.HOOK.beforeToAdd](crud, form) {
      this.$refs.addForm.addForm = { 'centerId': '1' }
      this.$refs.addForm.clusterList = [{ 'clusterFlag': '', 'clusterName': '', 'id': 1 }]
    }, [CRUD.HOOK.beforeToEdit](crud, form) {
      // this.handleCurrentChange(this.$refs.table.selection[0])
    }, changeMonitorFlag(cmFlag, centerId, monitorFlag) {
      const reqData = { 'cmFlag': cmFlag, 'centerId': centerId, 'monitorFlag': monitorFlag }
      clusterWh.upMonitorFlag(reqData).then(res => {
        this.$notify.success({
          title: '成功',
          message: '状态修改成功！',
          duration: 15000
        })
      }).catch(err => {
        this.$notify.error({
          title: '失败',
          message: '状态修改失败！',
          duration: 15000
        })
        if (err != null) {
          console.log(err.response.data.message)
        } else {
          console.log('请求失败!')
        }
      })
    }, refreshCluster(cmFlag, centerId, monitorFlag) {
      const currentSelect = this.$refs.table.selection
      if (JSON.stringify(currentSelect) === '[]') {
        this.$message('至少选中一条数据！')
        return
      }
      clusterWh.refreshCluster(currentSelect).then(res => {
        this.$notify.success({
          title: '成功',
          message: '集群主机配置信息刷新成功！',
          duration: 15000
        })
      }).catch(err => {
        this.$notify.error({
          title: '失败',
          message: '集群主机配置信息刷新失败！',
          duration: 15000
        })
        if (err != null) {
          console.log(err.response.data.message)
        } else {
          console.log('请求失败!')
        }
      })
    },
    upload(row) {
      this.open = true
      this.tableData.cmName = row.cmName
      this.tableList = row.clusterName.split(',')
    },
    closeApplyInfoDialog() {
      this.open = false
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    getList(file, fileList) {
      this.fileList = fileList
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      )
    },
    // beforeRemove(file, fileList) {
    //   return this.$confirm(`确定移除 ${file.name}？`)
    // },
    checkType(file) {
      console.log(file)
      if (file.name.split('.')[1] !== 'conf') {
        this.$message.error('只能上传conf格式文件')
        this.fileList = []
        return false
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('上传文件不能大于1M')
        this.fileList = []
        return false
      }
      return true
    },
    uploadData() {
      console.log(this.fileList, 'list')
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.append('cmName', this.tableData.cmName)
          formData.append('clusterName', this.tableData.clusterName)
          formData.append('file', this.fileList[0].raw)
          clusterWh.upLoad(formData).then((res) => {
            this.$notify.success({
              title: '成功',
              message: '上传成功'
            })
            this.open = false
          }).catch(() => {
            this.$notify.error({
              title: '错误',
              message: '上传失败'
            })
          })
        }
      })
    },
    libraryClose() {
      this.libraryForm = {
        cmFlag: '',
        clusterFlag: '',
        address: '',
        user: '',
        password: ''
      }
      this.libraryFlag = false
    },
    selectChange(selection, row) {
      if (selection.length > 1) {
        const del_row = selection.shift()
        this.$refs.table.toggleRowSelection(del_row, false)
      }
    },
    getAreaName(id) {
      switch (id) {
        case '1':
          return '金桥'
        case '2':
          return '万国'
      }
    }
  }
}
</script>

<style scoped>
</style>
